const app = getApp()
import { getAddres, getStsInformation, saveFile } from '../../api/index.js'
const uploadOss = require('../../utils/upload/uploadImg.js')
import { uuid } from '../../utils/util'
Page({
  data: {
    form: {
      supplierBrand: '',
      productIntroduce: '',
      productManualList: [],
      productPositioning: '',
      productTotalSale: '',
      businessCoverage: '',
      inDepartment: '',
      partyABrand: [''],
      partyACollection: [''],
      constructionBrand: [''],
      constructionCollection: [''],
      deliveryDay: '',
      needBilling: '',
      customerList: []
    },
    productPositioningList: [],
    inDepartmentList: [],
    needBillingList: [],
    partyABrand: '',
    partyACollection: '',
    constructionBrand: '',
    constructionCollection: '',
    fileList: [],
    qualityIndex: '',
    region: [],
    multiIndex: [],
    multiArray: [[], [], []],
    qualitys: [],
    province: '',
    city: '',
    area: '',
    productManuals: [],
    manuals: [], // 产品手册
  },
  async save() {},
	// async getSelectList() {
  //   try {
  //     const { ResultSet } = await getStsInformation()
  //     this.setData({
  //       selects: ResultSet.userData
  //     })
  //   } catch (err) {
  //     console.log(err)
  //   }
  // },
  changeCheckbox ({ detail }) {
    this.setData({
      'form.productPositioning': detail
    })
  },
  toggleCheckbox ({ target: { dataset: { index } } }) {
    const checkbox = this.selectComponent(`.checkboxes-${index}`)
    console.log(checkbox)
    checkbox.toggle()
  },
  noop () {},
  changeInput ({ detail: { value }, target: { dataset: { key } } }) {
    this.setData({
      ['form.' + key]: value
    })
  },
  delFormArray ({ target: { dataset: { key, index } } }) {
    this.data.form[key].splice(index, 1)
    this.setData({
      [`form.${key}`]: this.data.form[key]
    })
  },
  changeCustomInput ({ detail: { data, key } }) {
    this.setData({
      [`form.${key}`]: data
    })
  },
  changeAddInput ({ detail: { value }, target: { dataset: { key } } }) {
    this.setData({
      [`${key}`]: value
    })
  },
  changeChildInput ({ detail, target: { dataset: { key, index } } }) {
    this.data.form.customerList[index][key] = detail
    this.setData({
      'form.customerList': this.data.form.customerList
    })
  },
  addCustomerList () {
    this.data.form.customerList.unshift({
      customerName: '',
      specification: '',
      annualOrderAmount: ''
    })
    this.setData({
      'form.customerList': this.data.form.customerList
    })
  },
  addFormArray ({ target: { dataset: { key } } }) {
    this.data.form[key].push('')
    this.setData({
      [`form.${key}`]: this.data.form[key]
    })
  },
  changeRadio ({ detail, target: { dataset: { key } } }) {
    this.setData({
      [`form.${key}`]: JSON.parse(detail)
    })
  },
  preStep () {
    wx.$nav.navigateBack()
  },
  nextStep () {
    let filters = ['supplierBrand', 'productIntroduce', 'productTotalSale', 'businessCoverage', 'inDepartment', 'deliveryDay', 'needBilling']
    let filters2 = ['partyABrand', 'partyACollection', 'constructionBrand', 'constructionCollection', ]
    let valid = filters.every(key => this.data.form[key])
    let valid2 = filters2.every(key => {
      return this.data.form[key].every(item => item)
    })
    if (!valid || !valid2) {
      wx.showToast({ title: '请仔细检查是否有未填写的数据！', icon: 'none' })
      return
    }
    app.globalData.form = { ...app.globalData.form, ...this.data.form }
    wx.$nav.navigateTo('/pages/overview/index')
  },
  async againUpload ({ target: { dataset: { item, index } } }) {
    let _this = this
    let tempFiles = this.data.fileList
    tempFiles[index].success = ''
      _this.setData({
        fileList: tempFiles
      })
    let fileExtension = item.name.split('.')[item.name.split('.').length - 1]
    const fileUrl = await _this.uploadFile(item, 'path', tempFiles, index, _this)
    if (fileUrl) {
      const { ResultSet } = await saveFile({
        fileList: [{
          fileName: item.name,
          fileExtension: fileExtension,
          fileSize: item.size,
          fileUrl: fileUrl
        }]
      })
      tempFiles.splice(index, 1)
      _this.data.form.productManualList.push({
        uuid: item.uuid,
        fileName: item.name,
        fileId: ResultSet.userData.fileIdList[0].fileId,
        fileUrl: ResultSet.userData.fileIdList[0].fileUrl
      })
      _this.setData({
        fileList: tempFiles,
        'form.productManualList': _this.data.form.productManualList
      })
    } else {
      tempFiles[index].success = 1
      _this.setData({
        fileList: tempFiles
      })
    }
  },
  delFile ({ target: { dataset: { item, index } } }) {
    this.data.fileList.splice(index, 1)
    this.setData({
      fileList: this.data.fileList
    })
  },
  delSuccessFile ({ target: { dataset: { item, index } } }) {
    this.data.form.productManualList.splice(index, 1)
    this.setData({
      'form.productManualList': this.data.form.productManualList
    })
  },
  delCustomerList ({ target: { dataset: { index, key } } }) {
    this.data.form[key].splice(index, 1)
    this.setData({
      [`form.${key}`]: this.data.form[key]
    })
  },
  async addUpload () {
    let _this = this
    wx.chooseMessageFile({
      count: 9,
      type: 'file',
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        _this.data.fileList.push(...res.tempFiles)
        _this.setData({
          fileList: _this.data.fileList
        })
        let tempFiles = _this.data.fileList
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            let fileExtension = item.name.split('.')[item.name.split('.').length - 1]
            const fileUrl = await _this.uploadFile(item, 'path', tempFiles, index, _this, 'fileList')
            if (fileUrl) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileName: item.name,
                  fileExtension: fileExtension,
                  fileSize: item.size,
                  fileUrl: fileUrl
                }]
              })
              return {
                uuid: item.uuid,
                fileName: item.name,
                fileId: ResultSet.userData.fileIdList[0].fileId,
                fileUrl: ResultSet.userData.fileIdList[0].fileUrl
              }
            } else {
              tempFiles[index].success = 1
              _this.setData({
                fileList: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form.productManualList.push(...tempFileList)
        _this.data.form.productManualList.forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          fileList: tempFiles,
          'form.productManualList': _this.data.form.productManualList
        })
      }
    })
  },
  uploadFile (item, key, files, index, that, dataKey) {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (fileUrl) => {
          resolve(fileUrl)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  hideUpLoading (){
    wx.hideLoading()
    wx.showModal({
      title: '上传失败',
      content: '请重新上传',
      showCancel: false,
    })
  },
  onLoad () {
    const { form, dropDown } = app.globalData
    if (dropDown.inDepartmentList.length) {
      let newForm = { ...this.data.form, ...form }
      this.setData({
        inDepartmentList: dropDown.inDepartmentList,
        needBillingList: dropDown.needBillingList,
        productPositioningList: dropDown.productPositioningList
      })
      this.setData({
        form: newForm
      })
    } else {
      let newForm = { ...this.data.form, ...form }
      app.globalData.getDropDownCallback = res => {
        this.setData({
          inDepartmentList: app.globalData.dropDown.inDepartmentList,
          needBillingList: app.globalData.dropDown.needBillingList,
          productPositioningList: app.globalData.dropDown.productPositioningList,
        })
        this.setData({
          form: newForm
        })
      }
    }
  },
})
